package com.bigchun.seeland;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import bean.ContentDataBean;
import bean.GoodsBean;
import myapp.MyApp;
import myview.XCFlowLayout;
import util.MyLog;
import util.RequestManager;
import util.SystemStatusManager;

public class SearchActivity extends BaseActivity {


    private LinearLayout ll_reback;
    private Context context;
    private MyApp myapp;
    private String token;
    private List<GoodsBean.DataBean> temhottabList = new ArrayList<>();
    private XCFlowLayout flowlayout;
    private LayoutInflater mInflater;
    private EditText et_searchtab;
    private TextView tv_search;
    private LinearLayout ll_hot_searchtab;
    private String activityType = "";
    private String apptype = "";
    private String textData;
    private SharedPreferences sharedPreferences;
    private String showroom;
    private ContentDataBean.DataBean textContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_search);
        setTranslucentStatus();
        context = this;
        myapp = (MyApp) getApplicationContext();
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        mInflater = LayoutInflater.from(context);
        activityType = getIntent().getStringExtra("activityType");
        showroom = getIntent().getStringExtra("showroom");
        textData = sharedPreferences.getString("textData", "");



        initView();
        initLin();
        gethotTabData();


    }


    private void initView() {
        ll_reback = findViewById(R.id.ll_reback);
        flowlayout = findViewById(R.id.flowlayout);
        et_searchtab = findViewById(R.id.et_searchtab);
        tv_search = findViewById(R.id.tv_search);
        ll_hot_searchtab = findViewById(R.id.ll_hot_searchtab);
        TextView tv_title = findViewById(R.id.tv_title);
        TextView tv_hot_search = findViewById(R.id.tv_hot_search);
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            if ("0".equals(apptype)){
                if ("app".equals(activityType)){
                    et_searchtab.setHint(textContent.getInput_want_cj());
                    ll_hot_searchtab.setVisibility(View.GONE);
                }else{
                    et_searchtab.setHint(textContent.getInput_want_wood());
                    ll_hot_searchtab.setVisibility(View.VISIBLE);
                }
            }else if ("1".equals(apptype)){
                et_searchtab.setHint(textContent.getInput_want_cailiao());
            }
            tv_title.setText(textContent.getSearch());
//            et_searchtab.setHint(textContent.getInput_search_con());
            tv_search.setText(textContent.getSearch());
            tv_hot_search.setText(textContent.getHot_search());
        }


    }

    //只是关闭软键盘
    private void closeKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
    private void initLin() {
        ll_reback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = et_searchtab.getText().toString().trim();
                if ("".equals(activityType)){
                    String searchstr = et_searchtab.getText().toString().trim();
                    if (!"".equals(searchstr)){
                        Intent intent = new Intent(context,SearchResultActivity.class);
                        intent.putExtra("searchcontent",trim);
                        startActivity(intent);

                    }
                }else if ("app".equals(activityType)){
                    String searchstr = et_searchtab.getText().toString().trim();
                    if (!"".equals(searchstr)){
                        Intent intent = new Intent(context,SearchAppResultActivity.class);
                        intent.putExtra("searchcontent",trim);
                        startActivity(intent);

                    }
                }else if ("zhanting".equals(activityType)){
                    String searchstr = et_searchtab.getText().toString().trim();
                    if (!"".equals(searchstr)){
                        Intent intent = new Intent(context,SearchZhantingResultActivity.class);
                        intent.putExtra("searchcontent",trim);
                        intent.putExtra("showroom",showroom);
                        startActivity(intent);

                    }
                }
                closeKeyboard();

            }
        });
    }

    /**
     * 获取搜索内容标签
     */
    private void gethotTabData() {

        String url = myapp.getWebConfig() + "/api/index/hot_product";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temhottabList = new Gson().fromJson(data.toString(), new TypeToken<List<GoodsBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    Toast.makeText(context, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    break;
                case 2:

                    for (int m = 0; m < temhottabList.size(); m++) {
                        TextView tvview = (TextView) mInflater.inflate(
                                R.layout.item_searchtab, flowlayout, false);
                        tvview.setText(temhottabList.get(m).getStore_name());
//                        tvview.setTag(temhottabList.get(m).getId() + "=" + attr_list.get(m).getKind_id());
                        flowlayout.addView(tvview, m);

                        flowlayout.getChildAt(m).setOnClickListener(
                                new View.OnClickListener() {

                                    @Override
                                    public void onClick(View v) {
                                        String searchtab = ((TextView)v).getText().toString().trim();
                                        et_searchtab.setText(searchtab);
                                        et_searchtab.setSelection(searchtab.length());//将光标移至文字末尾
//                                        Intent intent = new Intent(context,SearchResultActivity.class);
//                                        intent.putExtra("searchcontent",searchtab);
//                                        startActivity(intent);

                                        if ("".equals(activityType)){
                                            String searchstr = et_searchtab.getText().toString().trim();
                                            if (!"".equals(searchstr)){
                                                Intent intent = new Intent(context,SearchResultActivity.class);
                                                intent.putExtra("searchcontent",searchtab);
                                                startActivity(intent);

                                            }
                                        }else if ("app".equals(activityType)){
                                            String searchstr = et_searchtab.getText().toString().trim();
                                            if (!"".equals(searchstr)){
                                                Intent intent = new Intent(context,SearchAppResultActivity.class);
                                                intent.putExtra("searchcontent",searchtab);
                                                startActivity(intent);

                                            }
                                        }else if ("zhanting".equals(activityType)){
                                            String searchstr = et_searchtab.getText().toString().trim();
                                            if (!"".equals(searchstr)){
                                                Intent intent = new Intent(context,SearchZhantingResultActivity.class);
                                                intent.putExtra("searchcontent",searchtab);
                                                intent.putExtra("showroom",showroom);
                                                startActivity(intent);

                                            }
                                        }

                                    }
                                });
                    }

                    break;
                case 3:



                    break;
                case 4:

                    break;
                case 11:
                    if (!islogin){
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
            }
        }
    };
private boolean islogin = false;
    /**
     * 设置状态栏背景状态
     */
    public  void setTranslucentStatus()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win =  getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }

}
